#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'dengqianyi'

import mainHelp
from startService import getGlobalIOLoop
import tornado.autoreload
import os

#提供监测xls的服务
class XlsReloadHelp(object):
    def __init__(self):
        # self._testIndex = 0
        self._xlsDict = dict()
        self.init()
        pass
    def init(self):
        #注册重启方法
        mainHelp.Connection.addEvents("onReceiveMessage",self.onReceiveMessage)
        #启动xls监测机制
        self.startMonitorXls()
        pass
    def onReceiveMessage(self,jsonObj):
        if jsonObj.get("msgType") != "XlsReloadHelp":
            return
        print "XlsReloadHelp onReceiveMessage",jsonObj
        self.msgHandler(jsonObj)
        pass
    def msgHandler(self,jsonObj):
        if jsonObj.get("msgFunc") == "reloadAll":
            self.reloadAll()
            return
        pass
    def addXlsToMonitor(self,xlsPath,monitorCb=None):
        _list = list()
        if self._xlsDict.get(xlsPath) == None:
            if os.path.isfile(xlsPath):
                _list.append(os.stat(xlsPath).st_mtime)
                if monitorCb != None:
                    _list.append(monitorCb)
                else:
                    _list.append(self.monitorDefaultCb)
                self._xlsDict[xlsPath] = _list #key,文件路径;value[0],文件最后修改时间,value[1]监测回调
        pass
    def monitorDefaultCb(self):
        #提供一个默认的监听返回函数
        self.reloadAll()
        pass
    def startMonitorXls(self):
        getGlobalIOLoop().add_timeout(300,self.moitorXlsRun)
        pass
    def moitorXlsRun(self):
        # print "XlsReloadHelp moitorXlsRun",self._testIndex
        for key,value in self._xlsDict.items():
             #获取文件的最后的修改时间
            try:
                _lastChangeTime = os.stat(key).st_mtime
                _curChangeTime = value[0]
                # print "_lastChangeTime,_curChangeTime",long(_lastChangeTime),long(_curChangeTime),long(_lastChangeTime) != long(_curChangeTime)
                if long(_lastChangeTime) !=  long(_curChangeTime):
                    value[1]()
                    return
            except Exception:
                getGlobalIOLoop().add_timeout(1000,self.moitorXlsRun)
                return
        # self._testIndex += 1
        getGlobalIOLoop().add_timeout(1000,self.moitorXlsRun)
        pass
    def reloadAll(self):
        print "XlsReloadHelp reloadAll Xls File,Subprocess restart.."
        self._xlsDict.clear()
        tornado.autoreload._reload()#重启子进程
        pass
    pass

g = None
def getInstance():
    global g
    if g == None:
        g = XlsReloadHelp()
    return g